﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SAICAPPWEB.Models;
using DapperExtensions;
namespace SAICAPPWEB.BLL
{
	public class TimeSheetBll:BaseBll<TimeSheet>
    {
		public Message SignIn(TimeSheet timesheet)
		{
			Message msg = new Message ();
			try{
			IList<IPredicate> predList = new List<IPredicate>();
			predList.Add(Predicates.Field<TimeSheet>(p => p.PhoneNo, Operator.Eq, timesheet.PhoneNo));
			predList.Add(Predicates.Field<TimeSheet>(p => p.PhoneSn, Operator.Eq, timesheet.PhoneSn));
				predList.Add(Predicates.Field<TimeSheet>(p => p.SignInTime,Operator.Lt ,DateTime.Parse(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"))));
				predList.Add(Predicates.Field<TimeSheet>(p => p.SignInTime,Operator.Gt ,DateTime.Parse( DateTime.Now.ToString("yyyy-MM-dd"))));

			IPredicateGroup ipg = Predicates.Group(GroupOperator.And, predList.ToArray());
				var ls=Db.GetList<TimeSheet>(ipg);
				var	result = Db.GetList<TimeSheet>(ipg).FirstOrDefault();
			if (result == null) {
				timesheet.SignInTime = DateTime.Now;
				Db.Insert (timesheet);	
					msg.message="签到成功！";
					msg.data=1;
			}
				else
				{
					msg.error = true;
					msg.message = "您今天已经签到，本次签到无效";
				}
			}
			catch(Exception ex) {
				msg.error = true;
				msg.message = ex.Message;
			}
			finally{
				Db.Connection.Close ();
			}
			return msg;
		}
		public Message SignOut(TimeSheet timesheet)
		{
			Message msg = new Message ();
			try{
				IList<IPredicate> predList = new List<IPredicate>();
				predList.Add(Predicates.Field<TimeSheet>(p => p.PhoneSn, Operator.Eq, timesheet.PhoneSn));
				predList.Add(Predicates.Field<TimeSheet>(p => p.SignInTime,Operator.Lt ,DateTime.Parse(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"))));
				predList.Add(Predicates.Field<TimeSheet>(p => p.SignInTime,Operator.Gt ,DateTime.Parse( DateTime.Now.ToString("yyyy-MM-dd"))));
				IPredicateGroup ipg = Predicates.Group(GroupOperator.And, predList.ToArray());
				var	result = Db.GetList<TimeSheet>(ipg).FirstOrDefault();
				if (result != null) {
					result.SignOutTime = DateTime.Now;
					Db.Update (result);
				}
				else
				{
					msg.error = true;
					msg.message = "您今天尚未签到，本次签退无效，请签到后再签退";
				}
			}
			catch(Exception ex) {
				msg.error = true;
				msg.message = ex.Message;
			}
			finally{
				Db.Connection.Close ();
			}
			return msg;
		}
    }
}